<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('taskList.rawMaterialInventory')"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<!--最上面的搜索内容-->
			<view class="distributed">
				<!-- 填写内容 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-scan">
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue"
							:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>
						<comboGrid requestUrl="/mes/basMaterial/getPageSetPDA" v-model="data.materialCode"
							:requestParam="data.materialParam" inputKey="materialName"
							:placeholder="$t('distributedEnter.placeholderTextChoose')" gridPlaceholder="输入代码或者名称筛选"
							:column="data.columnName.column" bindValue="materialCode" @setClick="getMaterialClick">
						</comboGrid>
						<uni-icons class="iconDelete" type="close" v-if="data.materialCode" size="18" color="#999"
							@click="handelMaterialClear"></uni-icons>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="width:180rpx">{{ $t('distributedOut.location') }}：</text>
						<storageBin :ignoreLocationCode="data.ignoreLocationCode" class="gui-text-right"
							requestUrl="/wms/wmsLocation/getIsUsePageSetByFG" :requestParam="data.requestParam"
							:locationUseList="data.locationUseList" v-model="data.locationCode"
							@setClick="getLocationClick" style="width:100%"></storageBin>
						<uni-icons class="iconDelete" type="close" v-if="data.locationCode.length" size="18"
							color="#999" @click="handelClear"></uni-icons>
					</view>
				</view>
				<!--结果区-->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll" @scrolltolower="scrolltolowerFn">
					<!--条码维度-->
					<view class="custom-form-card" v-for="(x, i) in data.barcodeData" :key="i">
						<uni-collapse v-model="data.value">
							<uni-collapse-item titleBorder="true" :show-animation="true" :name="''+i">
								<template v-slot:title>
									<view class="card-mini-head" style="display: flex;padding: 10px 0px">
										<text class="title-line"></text>
										<text>{{ $t('translationImage.serialNumber') }}:
											<uni-tag type="primary" :inverted="true" :text="i + 1"></uni-tag>
											<!--{{i+1}}-->
										</text>
										<view class="card-item-100">
											<text class="item-info-title">{{ $t('distributedEnter.barcode') }}：</text>
											<uni-tag type="primary" :text="x.barcode" :mark="true" />
											<!--{{x.barcode}}-->
										</view>
									</view>
								</template>
								<view class="content" style="margin-bottom: 20rpx;">
									<view class="custom-card-itemOne">
										<view class="card-item-80">
											<text
												class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{ x.materialCode }}
										</view>
									</view>
									<view class="custom-card-itemOne">
										<text
											class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{ x.materialName }}
									</view>
									<view class="custom-card-itemOne">
										<text
											class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ x.materialSpec }}
									</view>
									<view class="custom-card-itemOne">
										<view class="card-item-50" style="flex:0.4"><text
												class="item-info-title">{{ $t('finishInventory.stockQty') }}：</text>{{ x.stockQty }}
										</view>
										<view class="card-item-50" style="flex:0.6"><text
												class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ x.unit }}
										</view>
									</view>
									<view class="custom-card-itemOne">
										<view class="card-item-40" style="flex:0.4"><text
												class="item-info-title">{{ $t('finishInventory.warehouseCode') }}：</text>{{ x.warehouseCode }}
										</view>
										<view class="card-item-60" style="flex:0.6"><text
												class="item-info-title">{{ $t('finishInventory.locationCode') }}：</text>{{ x.locationCode }}
										</view>
									</view>
									<view class="divider"></view>
									<view class="custom-card-itemOne">
										<view style="margin-left: 73%;">
											<view class="btnCancel" v-if="x.ckeckFlag == 'Y'"
												@click="HandUnCheckPda(x, x.barcode)">
												{{ $t('finishInventory.cancel') }}</view>
											<view class="btnPanDian" v-else @click="RMCheck(x, x.barcode)">
												{{ $t('finishInventory.check') }}</view>
										</view>
									</view>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>

					<view v-if="data.noticeHooks" class="noticeHooks">
						{{ data.barcodeData.length == 0 ? $t('stockManage.notAvailable') : $t('stockManage.without') }}
					</view>
				</scroll-view>
			</view>

			<!-- 页面弹窗 -->
			<uni-popup ref="inputDialog" type="center" :mask-click="false">
				<view v-if="data.scanInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-itembox">
							<view class="input-dialog-item">
								<text style="color:red;width:300rpx">{{ $t('pageTranslation.realInventoryQtyNew')
									}}：</text><input class="input" type="number" style="color:red"
									v-model="data.scanInfo.checkNum"
									:placeholder="$t('pageTranslation.plsRealInventoryQty')" />
								<uni-icons class="iconDelete" style="margin-top:0" type="close" size="18" color="#999"
									@click="data.scanInfo.checkNum = null"></uni-icons>
							</view>
						</view>
						<view class="input-dialog-itembox">
							<view class="input-dialog-item">
								{{ $t('pageTranslation.chekStatus') }}：{{ data.scanInfo.ckeckFlag == "Y" ? "check" : "unCheck"
								}}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedOut.barcode') }}：{{ data.scanInfo.barcode }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialCode') }}：{{ data.scanInfo.materialCode }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialName') }}：{{ data.scanInfo.materialName }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialSpec') }}：{{ data.scanInfo.materialSpec }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.uom') }}：{{ data.scanInfo.unit }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialName') }}：{{ data.scanInfo.materialName }}
							</view>
							<!-- [[2022-10-27 SJM 改 -->
							<view class="input-dialog-item">
								{{ $t('pageTranslation.barcodeQty') }}：{{ data.scanInfo.stockQty
								}}<!-- {{data.scanInfo.currentQty}} -->
							</view>

							<!-- <view class="input-dialog-item">
							          {{$t('pageTranslation.barcodeStatus')}}：{{data.scanInfo.barcodeStatus}}
							        </view> -->
							<!-- 2022-10-27 SJM 改 ]] -->
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('calendar.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
							{{ $t('calendar.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import {
	navigate,
	navigateBack
} from '@/utils/routerSkip.js';
import {
	ref,
	reactive,
	toRaw,
	watch,
	computed,
	onMounted
} from 'vue';
import storageBin from '@/components/storageBin.vue';
import comboGrid from "@/components/comboGrid";
import {
	onShow,
	onLoad
} from '@dcloudio/uni-app';

import {
	TEST_URL,
	PROD_URL,
	IMG_BASE_URL
} from '@/constant/config.js'
import {
	TOKEN
} from '@/constant/index.js';
import {
	basPdaOperationLogFn
} from '@/utils/index.js';
import {
	OPERATION_COMMIT,
	OPERATION_SCAN
} from '@/constant/index.js'
import {
	getDataDictionaryFn,
	base64toFile
} from '@/utils/index.js'
//API引入
import {
	selectWmsCheckStocked,
	getDetailInfo,
	checkPDA,
	selectWmsCheckstockDByBarcodeAndCheckStockId,
	checkStockCommit
} from '@/api/api.js'
//扫描条码的引入
import pdaScan from '@/hooks/pdaScan.js'
import {
	useStore
} from "vuex";
import {
	forEach
} from '../../../uni_modules/u-ajax/js_sdk/lib/utils';

//国际化引入
import {
	useI18n
} from 'vue-i18n';
import UniTag from "../../../uni_modules/uni-tag/components/uni-tag/uni-tag.vue";
const {
	t
} = useI18n();

const {
	scan
} = pdaScan()

//注册组件
components: {
	storageBin,
		comboGrid
}
let inputDialog = ref(null)  //条码维度修改条码数量
let data = reactive({
	barcodeinfo: null,
	scanInfo: null, //扫描的条码信息
	billid: null, //盘点单的id
	billCode: '', //上级界面传过来的billCode
	scanValue: '', //扫描信息
	materialId: '', //物料id
	materialCode: '', //物料编码
	locationCode: '', //库位code
	locationId: '', //库位id
	locationName: '', //库位名称
	ignoreLocationCode: [],
	noticeHooks: false,
	isLoading: false,
	isFinish: false,
	barcodeData: [], //条码维度返回的信息
	value: ['0'], //card的展开
	page: 1,
	rows: 20,
	//物料代码的传参
	materialParam: {
		text: '',
		materialCode: "",
		materialName: "", //物料代码,传给接口用的变量
	},
	// 库位的传参
	requestParam: {
		locationCode: ""
	},
	//物料代码的下拉选择器
	columnName: {
		column: [{
			label: t('distributedEnter.materialCode'),
			name: "materialCode",
		}, {
			label: t('distributedEnter.materialName'),
			name: "materialName",
		}]
	},
	// 库位的下拉选择器
	columnLocation: {
		column: [{
			label: t('JsInternational.volumnStockName'),
			name: "locationCode",
		}, {
			label: t('JsInternational.volumnStockOf'),
			name: "maxCapacity",
		}]
	},
})
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	data.page = 1
	data.rows = 20
	selectMaterial(); //查询
})
onLoad((options) => {
	var keyword = options.keyword;
	var type = options.type;
	if (type == 2) //物料维度
	{
		data.materialCode = keyword
	}
	else {
		data.locationCode = keyword
		data.materialCode = options.materialCode
	}
	data.billCode = options.billCode
	data.billid = options.billid
})


// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}

// 获取code，查询barcode信息
const getCode = (code, type) => {
	let parmes = { //根据barcode查询物料详情
		barcode: data.scanValue,
		masterId: data.billid,
		locationCode: '',
		materialCode: ''
	}
	selectWmsCheckStocked(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品盘点'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status, //返回状态
				errorMessage: res.message, //错误信息
				isPass: res.status == 200 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.status == 200) {
			data.scanValue = code //扫描的条码
			data.page = 1
			data.rows = 20
			selectMaterial() // 去查询条码

		} else {
			uni.showToast({
				title: res.message,
				icon: "none"
			});
		}
	})
}

// 物料代码的选择
const getMaterialClick = (x) => {
	data.materialId = x.id
	data.materialCode = x.materialCode;
	data.page = 1
	data.rows = 20
	selectMaterial()

}

//库位选择之后赋值给变量
const getLocationClick = (x) => {
	data.locationId = x.id
	data.locationName = x.locationName;
	data.locationCode = x.locationCode;
	data.page = 1
	data.rows = 20
	selectMaterial()

}

//物料代码查询
const selectMaterial = () => {

	getDetailInfo({ //根据物料代码查询物料详情
		barcode: data.scanValue,
		billCode: data.billCode, //盘点单号
		locationCode: data.locationCode,
		materialCode: data.materialCode,
		checkFlag: '',
		page: data.page,
		rows: data.rows
	}).then(res => {
		data.isLoading = false;
		if (res.status == 200) {
			data.noticeHooks = false
			const rows = res.data.rows;
			if (data.page == 1) {
				if (rows.length == 0) {
					data.noticeHooks = true
				}
				data.barcodeData = rows

			} else {
				data.barcodeData.push(...rows)
			}
			data.barcodeData?.forEach((item,index)=>{
				if(index!=0){
					data.value.push(''+index)
				}
			})
			data.noticeHooks = data.barcodeData.length >= res.data.total
			data.isFinish = data.barcodeData.length >= res.data.total;
		}
	})
}

// 页面跳转到查看记录
const clickRight = () => {
	navigate({
		url: `/pages/finishedInventory/finishedInventoryRecord?id=${data.id}`
	})
}

const handelClear = () => {
	data.locationCode = ""
	data.locationName = ""
	data.locationId = null
	data.page = 1
	data.rows = 20
	selectMaterial()
}

const handelMaterialClear = () => {
	data.materialId = null
	data.materialCode = "";
	data.page = 1
	data.rows = 20
	selectMaterial()
}

// 下拉加载
const scrolltolowerFn = () => {
	if (!data.noticeHooks) {
		data.page++
		data.isLoading = true;
		selectMaterial()
	}
}

//点击盘点
const HandCheckPda = (x, keyword) => {
	var obj = {}
	obj.billCode = data.billCode;
	obj.barcode = keyword;
	obj.materialCode = "";
	obj.locationCode = ""
	obj.ckeckFlag = "Y"

	var res = submitCheckPda(obj, x);
	console.log(res)
}


//点击取消盘点
const HandUnCheckPda = (x, keyword) => {
	var obj = {}
	obj.billCode = data.billCode;
	obj.barcode = keyword;
	obj.materialCode = "";
	obj.locationCode = ""
	obj.ckeckFlag = "N"

	var res = submitCheckPda(obj, x);
	console.log(res)
}

//提交盘点数据
const submitCheckPda = (parmes, x) => {

	uni.showLoading({
		title: 'loading',
		mask: true
	});

	checkPDA(parmes).then(res => {
		uni.hideLoading();
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品盘点'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status, //返回状态
				errorMessage: res.message, //错误信息
				isPass: res.status == 200 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		console.log(res)
		if (res.status == 200) {

			if (parmes.ckeckFlag == "Y") {
				x.ckeckFlag = "Y"
			}

			if (parmes.ckeckFlag == "N") {
				x.ckeckFlag = "N"
			}
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: 'none',
				complete: () => {
					//selectMaterial() //重新执行查询
				}
			})

		} else {
			uni.showToast({
				title: res.message,
				icon: "none"
			});

		}
	})

}


//RM 仓库盘点
const RMCheck = (barcode) => {
	data.barcodeinfo = barcode
	let parmes = {
		barcode: barcode.barcode,
		selectType: 'checkStock',
		checkStockId: data.billid
	}
	selectWmsCheckstockDByBarcodeAndCheckStockId(parmes).then(res => {
		if (res.status == 200) {
			data.scanInfo = res.data;
			inputDialog.value.open()
		}
	})
}


const cancelFn = () => {
	data.scanInfo = undefined
	inputDialog.value.close()
}



// 扫码弹框确认信息
const scanConfirmFn = () => {
	if (!data.scanInfo.checkNum) {
		uni.showToast({
			title: t('pageTranslation.plsRealInventoryQty'),
			icon: 'none'
		})
		return
	}
	if (Number(data.scanInfo.checkNum) < 0) {
		uni.showToast({
			title: t('pageTranslation.realInventoryQtyLess'),
			icon: 'none'
		})
		return
	}
	let parmes = {
		id: data.billid,
		barcodeId: data.scanInfo.barcodeId, // 条码id
		barcode: data.scanInfo.barcode, // 条码
		checkQty: data.scanInfo.checkNum,
		batchNumber: data.scanInfo.batchNumber,
		remark: data.scanInfo.remarkText
	}
	checkStockCommit(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '盘点'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_CHECK_CODE
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			data.barcodeinfo.ckeckFlag = "Y"
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: 'none',
				complete: () => {
					//selectMaterial() //重新执行查询
				}
			})
		} else {
			uni.showToast({ title: res.message, icon: 'none' })
		}
	})
	inputDialog.value.close()
}


</script>

<style lang="scss" scoped>
// .card-my{
// 	display: flex;
// 	flex-direction: column;
// }
.addflex {
	display: flex;
	align-items: center;

	.itemflex {
		flex: 1;
	}
}

.distributed {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 200rpx);
	// height: 100vh;
}

.scroll {
	margin-top: 15rpx;
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: fixed;
}

.addborder {
	border: 1rpx solid #DCDFE6;
	box-sizing: border-box;
	padding: 15rpx;
	margin-bottom: 15rpx;
	border-radius: 8rpx;
}

.input-dialog-itembox {
	padding: 15rpx;
	box-sizing: border-box;
	border: 1rpx solid #DCDFE6;
	margin-bottom: 15rpx;
	border-radius: 8rpx;
}

.input-dialog-item {
	font-size: 24rpx;
}

.input,
.textarea {
	font-size: 24rpx;
}

.iconDelete {
	margin-top: 20rpx;
	height: 100%;
	width: 40rpx;
}

.item-info-title {
	margin-left: 10px;
}


.btnSuccess {
	width: 120rpx;
	height: 40rpx;
	line-height: 40rpx;
	color: #fff;
	background-color: #007aff;
	display: inline-block;
	text-align: center;
	border-radius: 10rpx;
}

.btnError {
	width: 120rpx;
	height: 40rpx;
	line-height: 40rpx;
	color: #fff;
	background-color: red;
	display: inline-block;
	text-align: center;
	border-radius: 10rpx;
}


.btnCancel {
	width: 120rpx;
	height: 40rpx;
	line-height: 40rpx;
	color: #fff;
	background-color: #f08d49;
	display: inline-block;
	text-align: center;
	border-radius: 10rpx;
}

.btnPanDian {
	width: 120rpx;
	height: 40rpx;
	line-height: 40rpx;
	color: #fff;
	background-color: #42b983;
	display: inline-block;
	text-align: center;
	border-radius: 10rpx;
}

.flexRight {

	display: flex;
	flex-direction: row;
	justify-content: flex-end;
}
</style>